package com.mediatecture.flex.component
{
	import mx.containers.Canvas;
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	
	[Event(name=ModifiedEvent.MODIFIED, type="com.ittconsult.flex.enforce.component.ModifiedEvent")]
	[Event(name=ModifiedEvent.SAVED, type="com.ittconsult.flex.enforce.component.ModifiedEvent")]
	[Event(name=ModifiedEvent.UNMODIFIED, type="com.ittconsult.flex.enforce.component.ModifiedEvent")]
	[Event(name=RequestCloseEvent.REQUEST_CLOSE, type="com.ittconsult.flex.enforce.component.RequestCloseEvent")]
	
	public class EditableComponent extends Canvas
	{
		protected var realLabel : String;
	
		public function isModified() : Boolean {
			return false;
		}
		
		public function edit() : Boolean {
			return true;
		}
		public function unedit() : Boolean {
			if ( isModified() ) {
				var message : String = "Екранът съдържа незаписана информация.\nЖелаете ли тя да бъде записана ?";  
				Alert.show( message, "Потвърждение", Alert.YES | Alert.NO | Alert.CANCEL, this, onAlertSaveBeforeUnedit, null, Alert.CANCEL );
				return false;
			}
			return true;
		}
		protected function onAlertSaveBeforeUnedit( event : CloseEvent ):void {
            if ( event.detail == Alert.YES ) {
                save();
                requestSave();
            } else if ( event.detail == Alert.NO ) {
            	//TODO: return old values
            }
  		}
  		protected function requestSave() : void {
			dispatchEvent( new  EditableComponentEvent( EditableComponentEvent.SAVED ) );
		}
		
		public function save() : Boolean {
		
			return true;
		}
		
		public function close() : Boolean {
			if ( isModified() ) {
				var message : String = "Екранът съдържа незаписана информация.\nЖелаете ли тя да бъде записана ?";  
				Alert.show( message, "Потвърждение", Alert.YES | Alert.NO | Alert.CANCEL, this, onAlertSaveBeforeClose, null, Alert.CANCEL );
				return false;
			}
			
			dispatchEvent( new EditableComponentEvent( EditableComponentEvent.CLOSED ));
			return true;
		}
		
		
		protected function onAlertSaveBeforeClose( event : CloseEvent ):void {
            if ( event.detail == Alert.YES ) {
                save();
                requestClose();
            } else if ( event.detail == Alert.NO ) {
            	requestClose();
            }
        }


		protected function requestClose() : void {
			dispatchEvent( new  EditableComponentEvent( EditableComponentEvent.REQUEST_CLOSE ) );
		}
		
		public function getLabel() : String {
			return this.realLabel + ( isModified() ?  " *" : "" );
		}
	}
}